package com.example.musicplayer.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.example.musicplayer.R;
import com.example.musicplayer.model.Music;
import com.example.musicplayer.model.MusicLrc;
import com.example.musicplayer.mycontroller.MusicController;
import com.example.musicplayer.myenum.EnumPlayMode;
import com.example.musicplayer.myenum.EnumPlayState;
import com.example.musicplayer.myinterface.IViewObserver;
import com.example.musicplayer.util.DataSaveLoad;
import com.example.musicplayer.util.MediaListUtil;


public class MainActivity extends Activity implements IViewObserver
{
	ImageButton findBtn;//查找
	ImageButton preBtn;//上一首
	ImageButton playBtn;//播放
	ImageButton nextBtn;//下一首
	Button randomBtn;//随机
	TextView musicMaxTimeTv;//总时间
	TextView musicCurrentTimeTv;//当前播放时间
	TextView musicNameTv;//音乐名
	EditText musicEt;//搜索框
	ListView musicListView ;//音乐列表
	SeekBar seekBar;//进度条
	TextView timerTextView;//定时
	AlertDialog alertDialog;//弹出框

	Music music;//音乐对象
	MusicController musicController;//音乐控制器
	boolean isExit=false;//是否退出
	MusicLrc musicLrc;//歌词对象
	Toast t;//Toast对象
	Menu menu;//菜单对象
	long leaveTime;//剩余时间
	EnumPlayMode mode;//播放模式

	@Override
	public void update()
	{
		handleMusicInfo.sendEmptyMessage(0);//Model改变通知
	}

	Handler handleMusicInfo=new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			setPlayState(music.getState());//设置播放状态
			setPlayMode(music.getMode());//设置播放模式
			setMusicName(music.getMusicName());//设置音乐名
			setTime(music.getSeekTime(), music.getTotalTime());//设置总时间
			setMusicLrc(music.getCurrentLrc());//设置歌词
			setSelectItem();//设置列表选择项
			setLeaveTime();//设置定时剩余时间
		}
	};

	/**
	 * 设置剩余时间定时显示
	 */
	public void setLeaveTime()
	{
		if (leaveTime == 0)
		{
			if (menu != null)
			{
				menu.removeItem(1);//去掉Id为1的Item
				menu.add(Menu.NONE, 1, 0, "定时关闭");//添加定时关闭项
			}
		}
		else
		{
			if (leaveTime > System.currentTimeMillis())
			{
				menu.removeItem(1);//去掉Id为1的Item
				long time=leaveTime - System.currentTimeMillis();//计算剩余时间
				Date date=new Date(time);
				menu.add(Menu.NONE, 1, 0, "定时关闭(" + String.format("%tM:%tS", date, date) + ")");//在菜单栏中添加剩余时间
				timerTextView.setText("定时关闭(" + String.format("%tM:%tS", date, date) + ")");//在弹出框中添加剩余时间
			}
			else
			{
				System.exit(0);
			}
		}
	}

	/**
	 * 设置选定的列表
	 */
	public void setSelectItem()
	{
		try
		{
			int index=musicController.getMusicIndex(music.getPath());//获取选择项的索引
			int n=musicListView.getFirstVisiblePosition();//获取列表开始显示位置
			int m=musicListView.getChildCount();//获取显示的列表项数
			for (int i=n;i < n + m;i++)
			{
				View v=musicListView.getChildAt(i - n);
				if (v != null)
				{
					if (i == index)
					{
						v.setBackgroundColor(Color.argb(100, 166, 166, 166));//如果被选中则显示这种颜色
					}
					else
					{
						v.setBackgroundColor(Color.argb(2, 5, 5, 5));//如果没被选中则显示这种颜色
					}
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}


	}

	/**
	 * 设置歌词
	 * @param lrc 歌词
	 */
	public void setMusicLrc(String lrc)
	{
		if (t == null)
		{
			//初始化Toast
			t = Toast.makeText(this, "", Toast.LENGTH_SHORT);
			//设置Toast的偏移
			t.setGravity(t.getGravity(), t.getXOffset(), t.getYOffset() + 100);
		}
		if (lrc != null)
		{
			t.setText(lrc);
			t.show();
		}
	}

	/**
	 * 设置播放状态
	 * @param playState 播放状态
	 */
	void setPlayState(EnumPlayState playState)
	{
		if (playState == EnumPlayState.PLAY)
		{
			playBtn.setImageResource(android.R.drawable.ic_media_pause);
		}
		else
		{
			playBtn.setImageResource(android.R.drawable.ic_media_play);
		}
	}

	/**
	 * 设置播放模式
	 * @param playMode 播放模式
	 */
	void setPlayMode(EnumPlayMode playMode)
	{
		if(playMode!=mode){
			switch (playMode)
			{
				case MODE_ORDER:
					randomBtn.setBackgroundResource(R.drawable.ic_order);
					Toast.makeText(this,"顺序播放",Toast.LENGTH_SHORT).show();
					break;
				case MODE_SINGLE_CYCLE:
					randomBtn.setBackgroundResource(R.drawable.ic_singlecircle);
					Toast.makeText(this,"单曲循环",Toast.LENGTH_SHORT).show();
					break;
				case MODE_RANDOM:
					randomBtn.setBackgroundResource(R.drawable.ic_random);
					Toast.makeText(this,"随机播放",Toast.LENGTH_SHORT).show();
					break;
				case MODE_ALL_CYCLE:
					randomBtn.setBackgroundResource(R.drawable.ic_allcircle);
					Toast.makeText(this,"循环播放",Toast.LENGTH_SHORT).show();
					break;
			}
			mode=playMode;
		}
	}

	/**
	 * 设置歌曲名
	 * @param musicName 歌曲名
	 */
	void setMusicName(String musicName)
	{
		musicNameTv.setText(musicName);
	}

	/**
	 * 设置当前时间，总时间以及进度条进度
	 * @param currentTime 当前时间
	 * @param totalTime 总时间
	 */
	void setTime(int currentTime, int totalTime)
	{
		seekBar.setMax(totalTime);
		seekBar.setProgress(currentTime);
		Date date = new Date(currentTime);
		musicCurrentTimeTv.setText(String.format("%tM:%tS", date,date));
		date = new Date(totalTime);
		musicMaxTimeTv.setText(String.format("%tM:%tS", date,date));
	}

	


    @Override
    public void onCreate(Bundle savedInstanceState)
	{
        super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme_Holo_Wallpaper);//设置主题
		
        setContentView(R.layout.music_list);//设置布局

		if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
			ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
		}
		
		findBtn = (ImageButton)findViewById(R.id.findImageButton);//通过Id查找控件
		findBtn.setImageResource(android.R.drawable.ic_menu_search);//通过Id查找控件


		preBtn = (ImageButton)findViewById(R.id.mainPreImageButton);//通过Id查找控件
		preBtn.setImageResource(android.R.drawable.ic_media_previous);//通过Id查找控件
		//按钮点击监听
		preBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					musicController.playPreMusic();//播放上一首音乐
				}
			});

		playBtn = (ImageButton)findViewById(R.id.mainPlayImageButton);//通过Id查找控件
		
		playBtn.setImageResource(android.R.drawable.ic_media_play);//通过Id查找控件
		//设置点击监听
		playBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					musicController.playMusic();//播放音乐
				}
			});

		nextBtn = (ImageButton)findViewById(R.id.mainNextImageButton);//通过Id查找控件
		nextBtn.setImageResource(android.R.drawable.ic_media_next);//设计ImageButton图片资源
		nextBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					musicController.playNextMusic();//播放下一首音乐
				}
			});

		randomBtn = (Button)findViewById(R.id.mainRandomButton);
		randomBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					musicController.onModeBtnClick();//切换模式
				}
			});

		musicMaxTimeTv = (TextView)findViewById(R.id.musicTotalTimeTextView);//通过Id查找控件
		musicCurrentTimeTv = (TextView)findViewById(R.id.musicCurrentTimeTextView);//通过Id查找控件
		musicNameTv = (TextView)findViewById(R.id.mainMusicNameTextView);//通过Id查找控件
		//设置点击监听
		musicNameTv.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					if (musicController.getMusicIndex(music.getPath()) > 2)
					{
						musicListView.setSelection(musicController.getMusicIndex(music.getPath()) - 2);//设置被选择项处于中间位置
					}
					else
					{
						musicListView.setSelection(0);
					}

				}
			});

		musicListView = (ListView)findViewById(R.id.mainListView);//通过Id查找控件
		//设置触摸监听
		musicListView.setOnTouchListener(new OnTouchListener(){
				float x1 = 0,y1 = 0,x2 = 0,y2 = 0;
				boolean isFirst=true;
				@Override
				public boolean onTouch(View p1, MotionEvent p2)
				{
					/**
					 * 如果手指从左往右滑动一段距离则跳转到视频播放界面
					 */
					if(p2.getAction()==MotionEvent.ACTION_DOWN){
						x1=p2.getX();
						y1=p2.getY();
						isFirst=true;
					}else if(p2.getAction()==MotionEvent.ACTION_MOVE){
						if(isFirst){
							x2=p2.getX();
							y2=p2.getY();
							if(x2-x1>30&&Math.abs(y2-y1)<15){
								music.stop();
								Intent intent=new Intent(MainActivity.this,VideoListActivity.class);
								startActivity(intent);
								isFirst=false;
								return true;
							}
						}
					}else if(p2.getAction()==MotionEvent.ACTION_UP){
						if(!isFirst){
							return true;
						}
					}
					
					return false;
				}
			});
		TextView t=(TextView)findViewById(R.id.empty);//通过Id查找控件
		musicListView.setEmptyView(t);//设置列表为空时的视图
		musicListView.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
				{
					musicController.setMusicIndex(p3);
				}
			});
		//设置滚动监听
		musicListView.setOnScrollListener(new AbsListView.OnScrollListener(){

				@Override
				public void onScrollStateChanged(AbsListView p1, int p2)
				{
				}

				@Override
				public void onScroll(AbsListView p1, int p2, int p3, int p4)
				{
					MainActivity.this.setSelectItem();
				}
			});


		musicEt = (EditText)findViewById(R.id.mainEditText);//通过Id查找控件
		//设置文字改变监听
		musicEt.addTextChangedListener(new TextWatcher(){

				@Override
				public void beforeTextChanged(CharSequence p1, int p2, int p3, int p4)
				{
				}

				@Override
				public void onTextChanged(CharSequence p1, int p2, int p3, int p4)
				{
					loadData(p1.toString());
				}

				@Override
				public void afterTextChanged(Editable p1)
				{
				}
			});

		seekBar = (SeekBar)findViewById(R.id.mainSeekBar);//通过Id查找控件
		//设置进度条拖动监听
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

				@Override
				public void onProgressChanged(SeekBar p1, int p2, boolean p3)
				{

				}

				@Override
				public void onStartTrackingTouch(SeekBar p1)
				{
				}

				@Override
				public void onStopTrackingTouch(SeekBar p1)
				{
					musicController.setSeekTime(p1.getProgress());
				}
			});

		
		
    }

    /**
     * 初始化音乐播放器、控制器
     */
	public void init()
	{
		music = Music.getInstance();
		music.registerViewObserver(this);
		musicController = new MusicController(this, music);
	}

	/**
	 * 获取音乐列表
	 * @param args 不定项参数
	 * @return 音乐列表
	 */
	public ArrayList<String> getMusicList(String ...args){

		ArrayList<String> list;
		if (args.length > 0)
		{
			list = musicController.getMusicList(args[0]);
		}
		else
		{
			list = musicController.getMusicList();
		}

		return list;
	}


	/**
	 * 将数据填充到ListView中
	 * @param list 数据列表
	 */
	public void fillData(ArrayList<String> list)
	{
		String from[]={"musicName","musicSinger"};
		int to[]={R.id.musicNameTextView,R.id.musicSingerTextView};
		List<Map<String,String>> data=new ArrayList<Map<String,String>>();
		for (String fileName:list)
		{
			String musicName="";
			String musicSinger="";
			if(fileName.contains("-")){
				musicName=fileName.split("-")[1];
				musicSinger=fileName.split("-")[0];
			}else{
				musicSinger="未知歌手";
				musicName=fileName.split("-")[0];
			}

			Map map=new HashMap();
			map.put("musicName", musicName);
			map.put("musicSinger", musicSinger);
			data.add(map);
		}
		SimpleAdapter simpleAdapter=new SimpleAdapter(this, data, R.layout.music_item, from, to);
		musicListView.setAdapter(simpleAdapter);
	}
	
	
	/**
	 * 加载音乐播放信息
	 */
	public void loadMusicInfo(){
		SharedPreferences sp= getSharedPreferences("music",Context.MODE_PRIVATE);
		int index=sp.getInt("index",0);
		int time=sp.getInt("time",0);
		musicController.setMusicIndex(index);
		musicController.setSeekTime(time);
		music.pause();
	}
	
	/**
	 * 加载数据
	 * @param args 不定项参数
	 */
	public void loadData(String ...args){
		AlertDialog.Builder b=new AlertDialog.Builder(this);
		ProgressBar p=new ProgressBar(this);
		b.setView(p);
		b.setMessage("正在更新中…");
		alertDialog=b.show();
		new RefreshMusicList(args).start();
	}

	/**
	 * 更新音乐列表类
	 * @author hyh
	 *
	 */
	class RefreshMusicList extends Thread
	{
	
		String args[];
		
		public RefreshMusicList(String ...args){
			this.args=args;
		}
		@Override
		public void run()
		{
			
			ArrayList<String> list=getMusicList(args);
			Message m=new Message();
			m.obj=list;
			h.sendMessage(m);
		}
	}

	/**
	 * 处理数据加载
	 */
	Handler h=new Handler(){

		boolean isFirst=true;
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			ArrayList list=(ArrayList)msg.obj;
			fillData(list);
			if(isFirst){
				loadMusicInfo();
				isFirst=false;
			}
			alertDialog.dismiss();
		}

	};

	//回到界面后重新加载数据
	@Override
	protected void onResume()
	{
		super.onResume();
		init();
		loadData();
	}
	
	
	@Override
	protected void onStop()
	{
		super.onStop();
		save();//保存信息
		music.removeViewObserver(this);//移除监听
	}

	@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
	@Override
	protected void onPause()
	{
		super.onPause();
		notice(music.getMusicName(), music.getSinger());
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		music.stop();
	}

	/**
	 * 保存当前音乐播放信息
	 */
	public void save(){
		SharedPreferences sp= getSharedPreferences("music",Context.MODE_PRIVATE);//新建SharedPreferences对象
		SharedPreferences.Editor edit= sp.edit();//获取编辑器
		edit.putInt("index",musicController.getMusicIndex(music.getPath()));//储存索引数据
		edit.putInt("time",music.getSeekTime());//储存时间数据
		edit.commit();
	}
	
	//监听返回键
	@Override
	public void onBackPressed()
	{
		if (isExit)
		{
			save();
			System.exit(0);
		}
		else
		{
			Toast.makeText(this, "再按一下退出!", Toast.LENGTH_SHORT).show();
			isExit = true;
			Timer timer=new Timer();
			timer.schedule(new TimerTask(){

					@Override
					public void run()
					{
						isExit = false;
					}
				}, 2000);
		}
	}


	//状态栏通知
	@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
	public void notice(String musicName, String singer)
	{
		NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);//获取消息通知服务
		Notification.Builder b=new Notification.Builder(this);//新建Notification.Builder对象
		b.setAutoCancel(true);//设置点击后自动取消
		PendingIntent p =PendingIntent.getActivity(this, 0, getIntent(), PendingIntent.FLAG_UPDATE_CURRENT);//获取PendingIntent对象
		b.setContentIntent(p);
		b.setContentText(singer);
		b.setContentTitle(musicName);
		b.setSmallIcon(R.drawable.image1);
		b.setWhen(System.currentTimeMillis());
		b.setDefaults(Notification.DEFAULT_LIGHTS);
		Notification n=b.build();
		notificationManager.notify(1, n);

	}
	
	//创建菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		this.menu = menu;
		menu.add(Menu.NONE, 1, 0, "定时关闭");
		menu.add(Menu.NONE, 2, 1, "更新音乐");
		return true;
	}


	//菜单项被选择监听
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == 1)
		{
			AlertDialog.Builder builder=new AlertDialog.Builder(this);//新建AlertDialog.Builder对象
			LayoutInflater inflater=LayoutInflater.from(this);//新建布局管理器
			View v=inflater.inflate(R.layout.timer, null);//通过布局获得视图
			timerTextView = (TextView)v.findViewById(R.id.timerTextView);//通过Id获得控件
			ListView listView =(ListView)v.findViewById(R.id.timerListView);//通过Id获得控件
			String items[]={"无","10分钟","20分钟","30分钟","40分钟","50分钟","60分钟"};
			ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, items);
			listView.setAdapter(adapter);//设置适配器
			listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//设置为单选模式
			builder.setView(v);//设置视图
			builder.setNegativeButton("取消", null);//设置取消按钮 
			final AlertDialog dialog =builder.show();
			//ListView监听
			listView.setOnItemClickListener(new OnItemClickListener(){

					@Override
					public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
					{
						if (p3 == 0)
						{
							leaveTime = 0;
						}
						else
						{
							leaveTime = p3 * 10 * 60 * 1000 + System.currentTimeMillis();
						}
						dialog.dismiss();

					}
				});
		}else if (item.getItemId() == 2){
			DataSaveLoad.delete("nameList"+ MediaListUtil.TYPE_MUSIC);
			DataSaveLoad.delete("pathList"+MediaListUtil.TYPE_MUSIC);
			loadData();
		}
		return true;
	}
	
	

}
